<template>
  <view class="notifications-container">
    <!-- 头部 -->
    <view class="header">
      <text class="header-title">消息中心</text>
      <button class="clear-all-btn" @click="clearAllNotifications" v-if="notifications.length > 0">
        清空全部
      </button>
    </view>

    <!-- 通知列表 -->
    <view class="notifications-list">
      <view 
        v-for="(notification, index) in notifications" 
        :key="notification.id"
        class="notification-item"
        :class="{ 'unread': !notification.isRead }"
        @click="handleNotificationClick(notification)"
      >
        <view class="notification-icon">
          <text class="icon-text">{{ getNotificationIcon(notification.type) }}</text>
        </view>
        
        <view class="notification-content">
          <view class="notification-header">
            <text class="notification-title">{{ notification.title }}</text>
            <text class="notification-time">{{ formatTime(notification.timestamp) }}</text>
          </view>
          <text class="notification-message">{{ notification.message }}</text>
          <view v-if="notification.data" class="notification-data">
            <text class="data-text">{{ formatNotificationData(notification) }}</text>
          </view>
        </view>
        
        <view class="notification-actions">
          <button 
            class="action-btn" 
            @click.stop="markAsRead(notification)"
            v-if="!notification.isRead"
          >
            标记已读
          </button>
          <button 
            class="action-btn delete" 
            @click.stop="deleteNotification(notification)"
          >
            删除
          </button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="notifications.length === 0" class="empty-state">
      <text class="empty-icon">��</text>
      <text class="empty-text">暂无消息</text>
      <text class="empty-desc">您还没有收到任何通知</text>
    </view>

    <!-- 通知设置弹窗 -->
    <view v-if="showSettingsModal" class="modal-overlay" @click="closeSettingsModal">
      <view class="modal-container" @click.stop>
        <view class="modal-header">
          <text class="modal-title">通知设置</text>
          <button class="close-btn" @click="closeSettingsModal">✕</button>
        </view>
        <view class="modal-content">
          <view class="setting-item">
            <text class="setting-label">允许通知</text>
            <switch 
              :checked="notificationSettings.enabled" 
              @change="toggleNotifications"
            />
          </view>
          <view class="setting-item">
            <text class="setting-label">聊天消息通知</text>
            <switch 
              :checked="notificationSettings.chatEnabled" 
              @change="toggleChatNotifications"
            />
          </view>
          <view class="setting-item">
            <text class="setting-label">好友请求通知</text>
            <switch 
              :checked="notificationSettings.friendRequestEnabled" 
              @change="toggleFriendRequestNotifications"
            />
          </view>
          <view class="setting-item">
            <text class="setting-label">积分变动通知</text>
            <switch 
              :checked="notificationSettings.pointsEnabled" 
              @change="togglePointsNotifications"
            />
          </view>
          <view class="setting-item">
            <text class="setting-label">系统通知</text>
            <switch 
              :checked="notificationSettings.systemEnabled" 
              @change="toggleSystemNotifications"
            />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import notificationService from '../../utils/notification-service.js'

export default {
  data() {
    return {
      notifications: [],
      showSettingsModal: false,
      notificationSettings: {
        enabled: true,
        chatEnabled: true,
        friendRequestEnabled: true,
        pointsEnabled: true,
        systemEnabled: true
      }
    }
  },
  
  onLoad() {
    this.loadNotifications()
    this.loadSettings()
    this.requestNotificationPermission()
  },
  
  onShow() {
    this.loadNotifications()
    // 清除红点和角标
    this.clearNotificationBadge()
  },
  
  methods: {
    // 加载通知列表
    loadNotifications() {
      try {
        const savedNotifications = uni.getStorageSync('notifications')
        if (savedNotifications) {
          this.notifications = JSON.parse(savedNotifications)
        }
      } catch (error) {
        console.error('加载通知失败:', error)
      }
    },
    
    // 保存通知列表
    saveNotifications() {
      try {
        uni.setStorageSync('notifications', JSON.stringify(this.notifications))
      } catch (error) {
        console.error('保存通知失败:', error)
      }
    },
    
    // 加载设置
    loadSettings() {
      try {
        const savedSettings = uni.getStorageSync('notificationSettings')
        if (savedSettings) {
          this.notificationSettings = JSON.parse(savedSettings)
        }
      } catch (error) {
        console.error('加载通知设置失败:', error)
      }
    },
    
    // 保存设置
    saveSettings() {
      try {
        uni.setStorageSync('notificationSettings', JSON.stringify(this.notificationSettings))
      } catch (error) {
        console.error('保存通知设置失败:', error)
      }
    },
    
    // 请求通知权限
    async requestNotificationPermission() {
      try {
        const granted = await notificationService.requestPermission()
        if (!granted) {
          uni.showToast({
            title: '请允许通知权限',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('请求通知权限失败:', error)
      }
    },
    
    // 处理通知点击
    handleNotificationClick(notification) {
      // 标记为已读
      if (!notification.isRead) {
        this.markAsRead(notification)
      }
      
      // 根据通知类型跳转
      const data = notification.data || {}
      switch (data.type) {
        case 'chat':
          uni.navigateTo({
            url: `/pages/chat/chat?userId=${data.userId}&userName=${data.userName}`
          })
          break
          
        case 'friend_request':
          uni.navigateTo({
            url: '/pages/friends/requests/requests'
          })
          break
          
        case 'points':
          uni.navigateTo({
            url: '/pages/points/points'
          })
          break
          
        case 'game':
          uni.navigateTo({
            url: '/pages/game/list/list'
          })
          break
          
        default:
          uni.switchTab({
            url: '/pages/index/index'
          })
      }
    },
    
    // 标记为已读
    markAsRead(notification) {
      notification.isRead = true
      this.saveNotifications()
    },
    
    // 删除通知
    deleteNotification(notification) {
      const index = this.notifications.indexOf(notification)
      if (index > -1) {
        this.notifications.splice(index, 1)
        this.saveNotifications()
        uni.showToast({
          title: '通知已删除',
          icon: 'success'
        })
      }
    },
    
    // 清空所有通知
    clearAllNotifications() {
      uni.showModal({
        title: '清空通知',
        content: '确定要清空所有通知吗？',
        success: (res) => {
          if (res.confirm) {
            this.notifications = []
            this.saveNotifications()
            uni.showToast({
              title: '通知已清空',
              icon: 'success'
            })
          }
        }
      })
    },
    
    // 获取通知图标
    getNotificationIcon(type) {
      const iconMap = {
        'chat': '💬',
        'friend_request': '👥',
        'points': '💰',
        'system': '⚙️',
        'game': '🎮'
      }
      return iconMap[type] || '🔔'
    },
    
    // 格式化通知数据
    formatNotificationData(notification) {
      const data = notification.data || {}
      switch (data.type) {
        case 'chat':
          return `来自: ${data.userName}`
        case 'friend_request':
          return `请求者: ${data.userName}`
        case 'points':
          return `积分: ${data.points > 0 ? '+' : ''}${data.points}`
        case 'game':
          return `游戏: ${data.gameType}`
        default:
          return ''
      }
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else if (diff < 7 * 86400000) { // 7天内
        return `${Math.floor(diff / 86400000)}天前`
      } else {
        return date.toLocaleDateString()
      }
    },
    
    // 设置相关方法
    showSettingsModal() {
      this.showSettingsModal = true
    },
    
    closeSettingsModal() {
      this.showSettingsModal = false
    },
    
    toggleNotifications(e) {
      this.notificationSettings.enabled = e.detail.value
      this.saveSettings()
    },
    
    toggleChatNotifications(e) {
      this.notificationSettings.chatEnabled = e.detail.value
      this.saveSettings()
    },
    
    toggleFriendRequestNotifications(e) {
      this.notificationSettings.friendRequestEnabled = e.detail.value
      this.saveSettings()
    },
    
    togglePointsNotifications(e) {
      this.notificationSettings.pointsEnabled = e.detail.value
      this.saveSettings()
    },
    
    toggleSystemNotifications(e) {
      this.notificationSettings.systemEnabled = e.detail.value
      this.saveSettings()
    },
    
    // 清除通知角标
    clearNotificationBadge() {
      try {
        // 将所有通知标记为已读
        const notifications = this.notifications.map(notification => {
          return { ...notification, isRead: true }
        })
        
        // 保存更新后的通知
        uni.setStorageSync('notifications', JSON.stringify(notifications))
        this.notifications = notifications
        
        // 清除红点和角标
        const tabIndex = 2 // 假设通知页面在tabBar的第3个位置
        
        // 隐藏红点
        uni.hideTabBarRedDot({
          index: tabIndex
        })
        
        // 移除badge
        if (typeof uni.removeTabBarBadge === 'function') {
          uni.removeTabBarBadge({
            index: tabIndex
          })
        }
      } catch (error) {
        console.error('清除通知角标失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.notifications-container {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 头部 */
.header {
  background: white;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #e0e0e0;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.clear-all-btn {
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 12rpx 20rpx;
  font-size: 24rpx;
}

/* 通知列表 */
.notifications-list {
  background: white;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.notification-item.unread {
  background: #f8f9ff;
  border-left: 4rpx solid #667eea;
}

.notification-item:active {
  background: #f8f9fa;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.icon-text {
  font-size: 28rpx;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.notification-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notification-time {
  font-size: 20rpx;
  color: #999;
  margin-left: 12rpx;
}

.notification-message {
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
  margin-bottom: 8rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.notification-data {
  margin-top: 8rpx;
}

.data-text {
  font-size: 20rpx;
  color: #999;
  background: #f8f9fa;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
}

.notification-actions {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  margin-left: 12rpx;
}

.action-btn {
  background: #f8f9fa;
  border: 1rpx solid #e9ecef;
  border-radius: 6rpx;
  padding: 8rpx 12rpx;
  font-size: 20rpx;
  color: #666;
  white-space: nowrap;
}

.action-btn.delete {
  color: #ff4757;
  border-color: #ff4757;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100rpx 40rpx;
  color: #999;
}

.empty-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #666;
  display: block;
  margin-bottom: 12rpx;
}

.empty-desc {
  font-size: 24rpx;
  opacity: 0.8;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  width: 90%;
  max-width: 500rpx;
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  background: #f8f9fa;
  border-bottom: 1rpx solid #e0e0e0;
}

.modal-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background: #e74c3c;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20rpx;
}

.modal-content {
  padding: 24rpx;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-label {
  font-size: 28rpx;
  color: #333;
}
</style>
